// https://www.lintcode.com/problem/merge-intervals/

/**
 * Definition of Interval:
 * public class Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 * }
 */

public class Solution {
    /**
     * @param intervals: interval list.
     * @return: A new interval list.
     */
    public List<Interval> merge(List<Interval> intervals) {
        // write your code here
        List<Interval> ret = new ArrayList<>();
        Collections.sort(intervals, new Comparator<Interval>() {
            @Override
            public int compare(Interval i_1, Interval i_2) {
                int diff = i_1.start - i_2.start;
                if (diff > 0) {
                    return 1;
                }
                else {
                    return (0 == diff) ? 0 : -1;
                }
            }
        });
        Interval tmp = null;
        for (Interval i : intervals) {
            if (null == tmp) {
                tmp = i;
            }
            else {
                if ((i.start >= tmp.start) && (i.start <= tmp.end)) {
                    if (i.end > tmp.end) {
                        tmp.end = i.end;
                    }
                }
                else {
                    ret.add(tmp);
                    tmp = i;
                }
            }
        }
        if (tmp != null) {
            ret.add(tmp);
        }
        return ret;
    }
}